package com.xwks.filter;

import com.xwks.entity.User;
import com.xwks.service.UserService;
import com.xwks.util.JwtUtil;
import com.xwks.util.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

public class JwtAuthenticationTokenFilter extends BasicAuthenticationFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    private final static String KEY = "key:";

    public JwtAuthenticationTokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {

            String token = request.getHeader(jwtUtil.getHeader());
            if (StringUtils.hasText(token)) {
                // 从自定义tokenProvider中解析用户
                Claims claims = jwtUtil.getClaimsByToken(token);
                String username = claims.getSubject();
                String redisToken = redisUtil.getCacheObject(KEY + username);
                if (!StringUtils.hasText(redisToken) || !token.equals(redisToken)) {
                    throw new RuntimeException("please sign in again");
                }
                User user = userService.getUserByUsername(username);
                if (Objects.isNull(user)) {
                    throw new RuntimeException("用户不存在");
                }
                Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), null, user.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            // 调用后续的Filter,若是上面的代码逻辑未能复原“session”，SecurityContext中没有想过信息，后面的流程会检测出"须要登陆"
            filterChain.doFilter(request, response);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
